package com.example.myapplication.ui.Home.fragments;

import android.view.View;
import android.widget.Button;

import com.example.myapplication.R;
import com.example.myapplication.base.BaseFragment;
import com.example.myapplication.model.buffr.DownInfo;
import com.example.myapplication.model.buffr.DownResultListenner;
import com.example.myapplication.model.buffr.DownState;
import com.example.myapplication.model.https.RetrofitDownloadManager;
import com.example.myapplication.ui.wight.UpdateDialog;
import com.example.myapplication.utils.NetworkUtil;

import butterknife.BindView;
import butterknife.OnClick;


public class UpdateFragment extends BaseFragment {
    @BindView(R.id.btn_update)
    Button btn_update;
    private UpdateDialog mUpdateDialog;
    //下载对象
    private DownInfo mDownInfo;
    //下载管理 - 记得 ondestory
    private RetrofitDownloadManager mRetrofitDownloadManager;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_update;
    }

    @Override
    protected void initView() {
        //下载管理者，因为我们这里只有一个更新版面，就不用判断 downinfo 属于哪个对象了
        mRetrofitDownloadManager = new RetrofitDownloadManager(new DownResultListenner() {
            @Override
            public void updateProgress(DownInfo info, int progress) {
                //放心年轻人。进度只有改变的时候，才会刷新
                mUpdateDialog.updateProgress(progress);
            }

            @Override
            public void updateState(DownInfo info, DownState state) {
                //刷新Dialog上面按钮状态
                mUpdateDialog.updateButtonState(info);
                if (state == DownState.FINISH) {
                    //下载完成，自动打开app安装
                    String path = info.getSavePath();
                    NetworkUtil.getInstance().installApk(path);
                }
            }
        });
        //更新Dialog
        mUpdateDialog = new UpdateDialog(
                getActivity(),
                R.drawable.update_circle,
                "1.2",
                "1.优化部分问题\n2.新增反馈",
                v -> {
                    //点击按钮，开始更新
                 mRetrofitDownloadManager.down(mDownInfo);
                });
        //下载对象 - 这种方式。一定要用這個
        mDownInfo = mRetrofitDownloadManager.createDownInfo("http://gdown.baidu.com/data/wisegame/41e4d8d8127bb502/baidushoujizhushou_16793302.apk");
        //不是新建,查看刷新 进度条。
        if(mDownInfo.getState() != DownState.NORMAL) {
            //已经下载过了。那么就刷新上面的进度条吧
            mUpdateDialog.updateProgress(mDownInfo.getProgress());
            //进度按钮
            mUpdateDialog.updateButtonState(mDownInfo);
        }
    }

    @Override
    public void showError(String msg) {

    }
    @OnClick({R.id.btn_update})
    public  void  onClick(View view){
        mUpdateDialog.show();
    }
}
